package com.quick.threadtest;

import java.util.concurrent.Semaphore;

public class SemaphoreTest {
    public static void main(String[] args) throws Exception{
        System.out.println("Action ... go!!");
        Semaphore semaphore = new Semaphore(5);
        for (int i = 0; i < 10; i++) {
          Thread thread = new Thread(new SemaphoreWorker(semaphore));
          thread.start();
        }
    }

}
class SemaphoreWorker implements Runnable{
    private String name;
    private Semaphore semaphore;
    public SemaphoreWorker(Semaphore semaphore){
        this.semaphore = semaphore;
    }
    @Override
    public void run() {
        try {
            log("is waiting for a permit!");
            semaphore.acquire();
            log("acquire a permit!");
            log("executed");
            Thread.sleep(100L);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            log("release a permit!");
            semaphore.release();
        }
    }
    private void log(String msg){
        if (name==null)
            name = Thread.currentThread().getName();
        System.out.println(name+" "+msg);
    }
}
